package com.presto.directo.utils

import android.app.Activity
import android.content.Intent
import android.text.*
import android.text.style.ClickableSpan
import android.view.View
import androidx.core.content.ContextCompat
import com.presto.directo.R

import com.presto.directo.entity.UserEntity
import com.presto.directo.mvvm.view.LoginPhoneActivity
import com.presto.directo.mvvm.view.WebActivity

object UserUtil {

    const val USER = "user"

    fun getUserId(): String {
        return SPUtil.getObject<UserEntity>(USER)?.user_id ?: ""
    }

    fun getUser(): UserEntity? {
        return SPUtil.getObject<UserEntity>(USER)
    }

    fun isLogin(): Boolean {
        return getUserId().isNotEmpty() && getUserId().isNotBlank()
    }

}

fun Activity.loginWith(needLogin: Boolean = true, block: (() -> Unit)? = null) {
    if (!needLogin || UserUtil.isLogin()) {
        block?.invoke()
    } else {
        val intent = Intent(this, LoginPhoneActivity::class.java)
        startActivity(intent)
    }
}

fun Activity.setTextClick(text: String, url: String, jump: (() -> Unit)? = null): SpannableString {
    val spanStr = SpannableString(text)
    val clickSpan = object : ClickableSpan() {
        override fun updateDrawState(ds: TextPaint) {
            ds.color = ContextCompat.getColor(this@setTextClick, R.color.color_accent)
            ds.isUnderlineText = true
        }

        override fun onClick(v: View) {
            if (jump == null) {
                val intent = Intent(this@setTextClick, WebActivity::class.java)
                intent.putExtra("url", url)
                intent.putExtra("title", text)
                this@setTextClick.startActivity(intent)
            } else {
                jump()
            }
        }
    }
    spanStr.setSpan(clickSpan, 0, text.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
    return spanStr
}